package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.CardWalletDao;
import cn.yunyichina.provider.bone.entity.CardWallet;
import cn.yunyichina.provider.bone.utils.BeanValidator;
import cn.yunyichina.provider.bone.vo.CardWalletVo;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.PersonalUser;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/1/16.
 */
@Service
public class CardWalletServiceImpl {

    private  static final Logger logger = LoggerFactory.getLogger(CardWalletServiceImpl.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private CardWalletDao cardWalletDao;


    /**
     * 获取卡包列表 - yyt.bone.card.wallet.list
     *
     * @param json
     * @return
     */
    public Response listCardWallet(String json) throws ValidateException {
        logger.info("获取卡包列表listCardWallet request json=" + json);
        List<CardWallet> cardWalletList;
        List<CardWallet> cardWalletsResponseList;
        Response response = new Response();
        try {
            CardWalletVo cardWalletVo = JsonUtils.parseObject(json, CardWalletVo.class);
            BeanValidator.validate(cardWalletVo);
            logger.info("获取卡包列表用户信息listCardWallet->request:userId="+cardWalletVo.getUserId());
            //获取用户名
            Map<String,String> mapUser = new HashMap<>(1);
            mapUser.put("id", cardWalletVo.getUserId());
            List<PersonalUser> listPersonalUser = BaseService.listPersonalUser(JsonUtils.toJsonString(mapUser));
            logger.info("获取卡包列表用户信息listCardWallet->response:"+JsonUtils.toJsonString(listPersonalUser));
            if (listPersonalUser != null && listPersonalUser.size() == 1) {
                String userId=listPersonalUser.get(0).getId();
                String userName=listPersonalUser.get(0).getUserName();
                CardWallet cw = new CardWallet();
                cw.setEnableFlag((short) 1).setUserId(cardWalletVo.getUserId());
                cardWalletList = cardWalletDao.select(cw);
                if (cardWalletList.size() < 1) {
                    //无卡包，插入数据
                    List<CardWallet> cardWalletListPo = new ArrayList<>();
                    for (int i = 0; i < 2; i++) {
                        CardWallet cardWalletPo = new CardWallet();
                        cardWalletPo.setId(PKGenerator.generateId()).setUserId(userId).setUserName(userName).
                                setOpenId(cardWalletVo.getOpenId()).setUseType((short) i).setTitle(cardWalletPo.getUseType() == 0 ? "影像问诊优惠券" : "健康顾问卡").
                                setContent(cardWalletPo.getUseType() == 0 ? "影像问诊优惠券" : "健康顾问卡").setUseCount(0).setTotalCount(cardWalletPo.getUseType() == 0 ? 1:1000).
                                setEnableFlag((short) 1).setExpiration(cardWalletPo.getUseType() == 0 ? simpleDateFormat.format(DateUtils.StringToDate("2018-3-31 23:59:59")) :
                                simpleDateFormat.format(DateUtils.StringToDate("2018-12-31 23:59:59"))).setStatus((short) 0).setCreatedTime(simpleDateFormat.format(new Date()));
                        cardWalletListPo.add(cardWalletPo);
                    }
                    logger.info("（患者卡包不存在）插入患者端卡包列表数据：" + JSON.toJSONString(cardWalletListPo));
                    cardWalletDao.batchInsert(cardWalletListPo);
                    logger.info("（患者卡包不存在）返回患者端卡包列表数据：" + JSON.toJSONString(cardWalletListPo));
                    response.setResult(JsonUtils.toJsonString(cardWalletListPo));
                } else {
                    cardWalletsResponseList = new ArrayList<>();
                    for (CardWallet var1 : cardWalletList) {
                        if (DateUtils.StringToDate(var1.getExpiration()).getTime() < System.currentTimeMillis()&&var1.getStatus()!=2) {
                            var1.setStatus((short) 2).setUpdateTime(simpleDateFormat.format(new Date()));
                            cardWalletDao.update(var1);
                        } else if (var1.getStatus() == (short) 0 ||
                                var1.getStatus() ==(short)1&& var1.getUseCount()+1<=var1.getTotalCount()&& var1.getUseType()==0
                                ||var1.getUseType()==1&&var1.getStatus() ==(short)1) {
                            var1.setExpiration(simpleDateFormat.format(DateUtils.StringToDate(var1.getExpiration())));
                            cardWalletsResponseList.add(var1);
                        }
                    }
                    logger.info("（患者卡包存在）返回患者端卡包列表数据：" + JSON.toJSONString(cardWalletsResponseList));
                    response.setResult(JsonUtils.toJsonString(cardWalletsResponseList));
                }
            }else{
                logger.info("卡包列表数据useId:{}(患者数据不存在)",cardWalletVo.getUserId());
                response.setResultCodeAndMessage("-1","患者数据不存在");
            }
        } catch (ValidateException e) {
            logger.error("参数为空:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("listCardWallet error", e);
            throw  e;
        }
        return response;
    }

}
